package org.ccg.servlet

import com.google.gson.GsonBuilder
import org.ccg.bean.SignalingMessage
import java.io.EOFException
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import javax.websocket.*
import javax.websocket.server.ServerEndpoint


@ServerEndpoint("/chat")
class ChatEndpoint {
    companion object {
        private val sessions = ConcurrentHashMap<String, Session>()

    }

    @OnOpen
    fun onOpen(session: Session) {
        var token = ""
        session.requestParameterMap["token"]?.let {
            token = it[0]
        }
        sessions[token] = session
        println("共多少人在线:" + sessions.size)
        sessions.forEach { (key, value) ->
            if (token != key) {
                value.asyncRemote.sendText("{\"type\":\"0\",\"sender\":\"${token}\"}")
            }
        }
        println("" + GsonBuilder().create().toJson(SignalingMessage(type = "0", sender = "", receiver = "", sdpMid = "", sdpMLineIndex = 0, sdp = "")))
    }

    @OnClose
    fun onClose(session: Session, closeReason: CloseReason) {
        //怎么获取关闭原因描述
        val statusCode: Int = closeReason.closeCode.code
        val token: String? = closeReason.reasonPhrase
        println("断开连接: ${token}")
        if (statusCode == 1000) {
            //如果是正常关闭,删除已保存的用户
            sessions.remove(token)
            sessions.forEach { (key, value) ->
                if (token != key) {
                    value.asyncRemote.sendText("{\"type\":\"1\",\"sender\":\"${token}\"}")
                }
            }
        }
        println("共多少人在线:" + sessions.size)
    }

    @OnMessage
    fun onMessage(jsonMessage: String, session: Session) {
        println("onMessage:     " + jsonMessage)
        try {
            val message = GsonBuilder().create().fromJson<SignalingMessage>(jsonMessage, SignalingMessage::class.java)
            when (message.type) {
                "OFFER", "ANSWER", "CANDIDATE" -> {
                    // 转发给指定的接收者
                    sessions[message.receiver]?.asyncRemote?.sendText(jsonMessage)
                }
            }
        } catch (e: Exception) {
            session.asyncRemote.sendText("""{"error": "Invalid message format"}""")
        }
    }

    @OnError
    fun onError(session: Session, error: Throwable) {
        if (error is EOFException) {
            // 客户端断开连接的处理
            println("客户端断开连接: " + session.getId())
        } else {
            println("WebSocket错误" + error)
        }
        try {
            session.close()
        } catch (e: Exception) {
            println("关闭会话时出错" + e)
        }
    }
}